package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.minio.MinIOFileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.utils.common.JsonUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOFileStorageService storageService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {

        if(content!=null && StringUtils.isNotEmpty(content)){
            try {
                //利用Freemarker生成静态页
                //1）读取.ftl模板文件
                Template template = configuration.getTemplate("article.ftl");

                //2）读取动态数据（模板文件需要数据）
                //把文章的content字段转换为List集合
                List<Map> list = JsonUtils.toList(content,Map.class);

                //将List存入Map集合（key:content）
                Map<String,Object> data = new HashMap<>();
                data.put("content",list);

                //3）生成静态页面(先缓存页面数据)
                StringWriter writer = new StringWriter();
                template.process(data,writer);

                //把静态页面文件存入MinIO
                //文件名：
                ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
                String url = storageService.uploadHtmlFile("",apArticle.getId()+".html",inputStream);

                //修改该文件的staticUrl字段值，为MiniO的访问路径
                apArticle.setStaticUrl(url);
                apArticleMapper.updateById(apArticle);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        }
    }
}
